package com.szmd.gradle;

import com.android.build.gradle.AppExtension;
import com.android.build.gradle.api.ApplicationVariant;
import com.szmd.gradle.tasks.PgyerUploadTask;
import com.szmd.gradle.tasks.SendMsgToDingTalkTask;

import org.gradle.api.Action;
import org.gradle.api.DomainObjectSet;
import org.gradle.api.Plugin;
import org.gradle.api.Project;


/**
 * created by : chentl
 * Date: 2021/01/07
 */
public class ReleaseHelperPlugin implements Plugin<Project> {

    public static final String ANDROID_EXTENSION_NAME = "android";
    public static final String sPluginExtensionName = "releaseHelper";

    @Override
    public void apply(Project project) {
        project.getExtensions().create(sPluginExtensionName, Extension.class, project);
        project.afterEvaluate(new Action<Project>() {
            @Override
            public void execute(Project project) {
                DomainObjectSet<ApplicationVariant> applicationVariants = ((AppExtension) project.getExtensions().findByName(ANDROID_EXTENSION_NAME)).getApplicationVariants();
                for (ApplicationVariant variant : applicationVariants) {
                    if (variant.getBuildType().getName().equalsIgnoreCase("release")) {
                        String variantName = variant.getName().substring(0, 1).toUpperCase() + variant.getName().substring(1);
                        //create pgyerUpload task
                        PgyerUploadTask pgyerUploadTask = project.getTasks().create("pgyUploadFor" + variantName, PgyerUploadTask.class);
                        pgyerUploadTask.init(variant, project);

                        //create dingtalk task
                        SendMsgToDingTalkTask sendMsgToDingTalkTask = project.getTasks().create("sendMsgToDingTalkFor" + variantName, SendMsgToDingTalkTask.class);
                        sendMsgToDingTalkTask.init(variant, project);

                        //dependency relationShip
                        variant.getAssembleProvider().get().dependsOn(project.getTasks().findByName("clean"));
                        pgyerUploadTask.dependsOn(variant.getAssembleProvider().get());
                        sendMsgToDingTalkTask.dependsOn(pgyerUploadTask);

                    }
                }

            }
        });
    }
}

